
package com.htd.htdapmservice.task;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.htd.htdapmapi.alarm.request.AlarmInto;
import com.htd.htdapmapi.alarm.result.AlarmResult;
import com.htd.htdapmcommon.constants.ErrorCodeConstants;
import com.htd.htdapmcommon.enums.AlarmSendStatus;
import com.htd.htdapmcommon.enums.AlarmsLevelEnum;
import com.htd.htdapmcommon.enums.AlarmsStatusEnum;
import com.htd.htdapmdmo.AlarmsInfo;
import com.htd.htdapmdmo.LogAnalyzeErrorRecord;
import com.htd.htdapmservice.service.intf.AlarmsInfoService;
import com.taobao.pamirs.schedule.IScheduleTaskDealMulti;
import com.taobao.pamirs.schedule.TaskItemDefine;

/**
 * 告警信息task
 */
@Component("alarmsInfoTask")
public class AlarmsInfoTask implements IScheduleTaskDealMulti<AlarmsInfo> {
    private static final Logger logger = LoggerFactory.getLogger(AlarmsInfoTask.class);

    @Autowired
    private AlarmsInfoService alarmsInfoService;


    private final static int HOURS = 1;

    /**
     *
     * @param alarmsInfos
     * @param ownSign
     * @return
     * @throws Exception
     */
    @Override
    public boolean execute(AlarmsInfo[] alarmsInfos, String ownSign) throws Exception {
        logger.info("alarmsInfoTask execute Entrance, itemBrands : {}, ownSign : {}", JSONObject.toJSONString(alarmsInfos), JSONObject.toJSONString(ownSign));
        boolean result = true;
        try {
            if (alarmsInfos!=null &&alarmsInfos.length>0) {
                AlarmInto alarmInto  =null;
                for (AlarmsInfo alarmsInfo:alarmsInfos) {
                    alarmInto= new AlarmInto();
                    alarmInto.setEventType(AlarmsStatusEnum.ALARM_TRIGGER.getCode());
                    alarmInto.setPriority(AlarmsLevelEnum.LEVEL_TWO.getCode());
                    alarmInto.setProductType(alarmsInfo.getAlarmsProductTypeCode());
                    alarmInto.setAlarmsDetail(alarmsInfo.getAlarmsDetail());
                    alarmInto.setAlarmsTitle(alarmsInfo.getAlarmsTitle());
                    AlarmResult alarmResult = alarmsInfoService.createAlarm(alarmInto);
                    if(ErrorCodeConstants.SUCCESS_CODE.equals(alarmResult.getResponseCode())){
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("sendStatus",AlarmSendStatus.SEND_YES);
                        map.put("alarmsId",alarmsInfo.getAlarmsId());
                        map.put("updateTime",new Date());
                        alarmsInfoService.updateSendStatusByAlarmsId(map);
                    }
                }
            }
        }catch (Exception e){
            logger.error("alarmsInfoTask.execute异常：{}",e.getMessage());
            return false;
        }
        return result;
    }

/**
     * 选择任务数据。
     * @param taskParameter 任务参数
     * @param ownSign 当前环境名称
     * @param taskQueueNum 当前任务类型的任务队列数量
     * @param taskItemList 当前调度服务器，分配到的可处理队列
     * @param eachFetchDataNum 每次获取数据的数量
     * @return
     * @throws Exception
     */

    @Override
    public List<AlarmsInfo> selectTasks(String taskParameter, String ownSign, int taskQueueNum, List<TaskItemDefine> taskItemList, int eachFetchDataNum) throws Exception {
        logger.info("alarmsInfoTask selectTasks Entrance, taskParameter : {}, ownSign : {}, taskQueueNum : {}, taskItemList : {}," +
                "eachFetchDataNum : {}", new Object[]{JSONObject.toJSONString(ownSign), JSONObject.toJSONString(taskParameter),
                JSONObject.toJSONString(taskQueueNum), JSONObject.toJSONString(taskItemList), JSONObject.toJSONString(eachFetchDataNum)});
        List<AlarmsInfo> alarmsInfoList = new ArrayList<AlarmsInfo>();
        try{
            List<String> taskIdList = new ArrayList<String>();
            Map<String, Object> paramMap = new HashMap<>();
            if (taskItemList != null && taskItemList.size() > 0) {
                for (TaskItemDefine taskItem : taskItemList) {
                    taskIdList.add(taskItem.getTaskItemId());
                }
                // 根据id和队列数取摩，在taskIdList中则被该任务查询并执行
                paramMap.put("taskQueueNum", taskQueueNum);
                paramMap.put("taskIdList", taskIdList);
                // 默认查询数量
                paramMap.put("rows", eachFetchDataNum > 0 ? eachFetchDataNum : 1000);
                //获取当前小时内的错误日志
                alarmsInfoList = alarmsInfoService.getAlarmsInfoListBySendStatus(AlarmSendStatus.SEND_NO.getCode());
            }
        } catch (Exception e){
            logger.error("alarmsInfoTask selectTasks error:", e);
        }
        return alarmsInfoList;
    }

    @Override
    public Comparator getComparator() {
        return new Comparator<LogAnalyzeErrorRecord>() {
            public int compare(LogAnalyzeErrorRecord o1, LogAnalyzeErrorRecord o2) {
                Long id1 = o1.getId();
                Long id2 = o2.getId();
                return id1.compareTo(id2);
            }
        };
    }

}


